package com.app.couponsharelife.utils

import android.annotation.SuppressLint
import android.app.Activity
import android.app.ActivityManager
import android.content.Context
import android.content.Context.TELEPHONY_SERVICE
import android.content.ContextWrapper
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.content.res.ColorStateList
import android.graphics.*
import android.graphics.drawable.Drawable
import android.net.ConnectivityManager
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.preference.PreferenceManager
import androidx.annotation.DrawableRes
import com.google.android.material.tabs.TabLayout
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.DrawableCompat
import android.telephony.TelephonyManager
import android.text.TextUtils
import android.util.Base64
import android.util.DisplayMetrics
import android.util.Log
import android.util.Log.i
import android.view.*
import android.view.inputmethod.InputMethodManager
import android.widget.LinearLayout
import android.widget.Scroller
import androidx.viewpager.widget.ViewPager
import com.gyf.barlibrary.ImmersionBar
import com.app.couponsharelife.R
import com.app.couponsharelife.data.bean.TaobaoGoodBean
import com.app.couponsharelife.data.bean.TaobaoTablePageBean
import com.app.couponsharelife.data.bean.UserCenterGoodBean
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.manage.Contacts.RETURN_RATIO
import com.app.couponsharelife.manage.MyApplication
import java.io.*
import java.lang.reflect.Field
import java.math.BigDecimal
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.text.DecimalFormat
import java.text.SimpleDateFormat
import java.util.*
import java.util.regex.Pattern


/**
 * Created by guluwa on 2018/3/15.
 */
object AppUtils {
    val df = DecimalFormat("#0.00")
    val simpleDateFormat = SimpleDateFormat("yyyy.MM.dd", Locale.getDefault())
    /**
     * 是否是手机号
     *
     * @return
     */
    fun isMobile(charSequence: CharSequence): Boolean {
        if (charSequence == null) return false
        //        return charSequence.toString().matches("0?(13|14|15|18)[0-9]{9}");
        val regex = "^1[3-9]\\d{9}$"
        val p = Pattern.compile(regex)
        val m = p.matcher(charSequence.toString())
        return m.matches()
    }
    /**
     * 是否是手机号
     *
     * @return
     */
    fun isChinese(charSequence: CharSequence): Boolean {
        if (charSequence == null) return false
        //        return charSequence.toString().matches("0?(13|14|15|18)[0-9]{9}");
        val regex = "[^\\\\x00-\\\\xff]+"
        val p = Pattern.compile(regex)
        val m = p.matcher(charSequence.toString())
        return m.matches()
    }
    /**
     * 获取当前时间
     *
     * @return 当前时间
     */
    fun getCurrentTime(): Int {
        val date = Date()
        val simpleDateFormat = SimpleDateFormat("HH", Locale.getDefault())
        return Integer.valueOf(simpleDateFormat.format(date))
    }

    fun getCurrentTime1(): String {
        val date = Date()
        val simpleDateFormat = SimpleDateFormat("yyyy.MM.dd.HH", Locale.getDefault())
        return simpleDateFormat.format(date)
    }

    fun getCurrentTime2(): String {
        val date = Date()
        val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
        return simpleDateFormat.format(date)
    }

    @SuppressLint("MissingPermission")
    fun getDeviceImei(): String {
        return (MyApplication.getContext().getSystemService(TELEPHONY_SERVICE) as TelephonyManager).deviceId
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    fun dip2px(context: Context, dpValue: Float): Int {
        val scale = context.resources.displayMetrics.density
        return (dpValue * scale + 0.5f).toInt()
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    fun px2dip(context: Context, pxValue: Float): Int {
        val scale = context.resources.displayMetrics.density
        return (pxValue / scale + 0.5f).toInt()
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     */
    fun sp2px(context: Context, spValue: Float): Int {
        val fontScale = context.resources.displayMetrics.scaledDensity
        return (spValue * fontScale + 0.5f).toInt()
    }
    /**
     * 将px值转换为sp值
     */
    fun px2sp(context: Context, pxValue: Float): Int {
        val fontScale = context.resources.displayMetrics.scaledDensity
        return (pxValue / fontScale + 0.5f).toInt()
    }
    //手机屏幕宽高
    fun getDisplayMetrics(context: Context): DisplayMetrics {
        val metric = DisplayMetrics()
        getActivity(context).windowManager.defaultDisplay.getMetrics(metric)
        return metric
    }
    //公里转换
    fun getKM(distance:Double):String{
        if (distance>1000){
            return "${df.format(distance/1000)}km"
        }else{
            return "${distance}m"
        }
    }
    private fun getActivity(c: Context): Activity {
        var context = c
        // Gross way of unwrapping the Activity so we can get the FragmentManager
        while (context is ContextWrapper) {
            if (context is Activity) {
                return context
            }
            context = context.baseContext
        }
        throw  IllegalStateException("The Context is not an Activity.")
    }

    //设置TabLayout的指示条margin,反射
    fun setIndicator(context: Context, tabs: TabLayout, leftDip: Int, rightDip: Int) {
        try {
            val tabLayout = tabs.javaClass
            val tabStrip: Field?
            tabStrip = tabLayout.getDeclaredField("slidingTabIndicator")
            tabStrip!!.isAccessible = true

            val ll_tab: LinearLayout?
            ll_tab = tabStrip.get(tabs) as LinearLayout

            val left = (getDisplayMetrics(context).density * leftDip).toInt()
            val right = (getDisplayMetrics(context).density * rightDip).toInt()

            for (i in 0 until ll_tab.childCount) {

                val child = ll_tab.getChildAt(i)

                //拿到tabView的mTextView属性
                /*var mTextViewField: Field?
                mTextViewField = child.javaClass.getDeclaredField("textView")
                mTextViewField!!.isAccessible = true
                val mTextView = mTextViewField.get(child) as TextView*/

                //因为我想要的效果是字多宽线就多宽，所以测量mTextView的宽度
                /*var width: Int
                width = mTextView.width
                if (width == 0) {
                    mTextView.measure(0, 0)
                    width = mTextView.measuredWidth
                }*/
                child.setPadding(0, 0, 0, 0)
                val params = child.layoutParams as LinearLayout.LayoutParams
                //params.width = width
                params.leftMargin = left
                params.rightMargin = right
                child.layoutParams = params
                child.invalidate()
            }
        } catch (e: IllegalAccessException) {
            e.printStackTrace()
        } catch (e: NoSuchFieldException) {
            e.printStackTrace()
        }
    }

    /**
     * 检测网络是否连接
     */
    val isNetConnected: Boolean
        get() {
            val cm = MyApplication.getContext().getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val networkInfo = cm.activeNetworkInfo
            if (networkInfo != null) {
                return true
            }
            return false
        }

    /**
     * MD5加密
     */
    fun encryptMD5(password: String): String {
        try {
            val instance: MessageDigest = MessageDigest.getInstance("MD5")//获取md5加密对象
            val digest: ByteArray = instance.digest(password.toByteArray())//对字符串加密，返回字节数组
            val sb = StringBuffer()
            for (b in digest) {
                val i: Int = b.toInt() and 0xff//获取低八位有效值
                var hexString = Integer.toHexString(i)//将整数转化为16进制
                if (hexString.length < 2) {
                    hexString = "0$hexString"//如果是一位的话，补0
                }
                sb.append(hexString)
            }
            return sb.toString()

        } catch (e: NoSuchAlgorithmException) {
            e.printStackTrace()
        }
        return ""
    }

    /**
     * 键值对转字符串
     */
    fun getMapString(paramsMap: Map<String, String>): String {
        val tm = TreeMap(paramsMap)
        val buffer = StringBuffer()
        tm.descendingMap().map {
            buffer.append(it.key).append("=").append(it.value).append("&")
        }
        buffer.append(Contacts.SERRET_VERSEC)
        return encryptMD5(buffer.toString())
    }

    //获取sharePreference String类型的值
    fun getString(key: String, defaultValue: String): String {
        val settings = PreferenceManager
                .getDefaultSharedPreferences(MyApplication.getContext())
        return settings.getString(key, defaultValue)
    }

    //设置sharePreference String类型的值
    fun setString(key: String, value: String) {
        val settings = PreferenceManager
                .getDefaultSharedPreferences(MyApplication.getContext())
        settings.edit().putString(key, value).apply()
    }

    fun parseParam(param: String): MutableMap<String, String>? {
        val params = param.substring(1, param.length - 1).split(",")
        val map = HashMap<String, String>()
        var sign = ""
        for (p in params) {
            if (p.substring(1, p.indexOf(":") - 1) != "sign") {
                map[p.substring(1, p.indexOf(":") - 1)] = p.substring(p.indexOf(":") + 2, p.length - 1)
            } else {
                sign = p.substring(p.indexOf(":") + 2, p.length - 1)
            }
        }
        return if (getMapString(map) != sign) null else map
    }

    // 将时间戳转为字符串
    fun getStrTime(stampTime: String): String {
        val sdf = SimpleDateFormat("yyyy.MM.dd")
        return sdf.format(Date(stampTime.toLong() * 1000L))
    }

    // 将时间戳转为字符串
    fun getStrTime1(stampTime: String): String {
        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm")
        return sdf.format(Date(stampTime.toLong() * 1000L))
    }

    // 将时间戳转为字符串
    fun getStrTime2(stampTime: String): String {
        val sdf = SimpleDateFormat("yyyy-MM-dd")
        return sdf.format(Date(stampTime.toLong() * 1000L))
    }

    // 将时间戳转为字符串
    fun getStrTime3(stampTime: String): String {
        val sdf = SimpleDateFormat("MM-dd HH:mm")
        return sdf.format(Date(stampTime.toLong() * 1000L))
    }

    // 将时间戳转为字符串
    fun getStrTime4(stampTime: String): String {
        val sdf = SimpleDateFormat("yyyy-MM-dd")
        return sdf.format(Date(stampTime.toLong()))
    }

    // 将时间戳转为字符串
    fun getStrTime5(stampTime: String): String {
        val sdf = SimpleDateFormat("MM-dd")
        return sdf.format(Date(stampTime.toLong() * 1000L))
    }

    fun getDistanceNowTime(stampTime: String): String {
        val distance = System.currentTimeMillis() / 1000 - stampTime.toLong()
        return when {
            distance < 60 -> "${distance}秒前"
            distance < 3600 -> "${distance / 60}分钟前"
            distance < 86400 -> "${distance / 3600}小时前"
            else -> "${distance / 86400}天前"
        }
    }
    //设置沉浸式状态栏
    fun initImmersionBar(activity: Activity, isBlack: Boolean) {
        ImmersionBar.with(activity).statusBarDarkFont(isBlack).init()
    }
    //退出销毁
    fun destroyImmersionBar(activity: Activity) {
        ImmersionBar.with(activity).destroy()
    }
    fun buildTransaction(type: String?): String {
        return if (type == null) System.currentTimeMillis().toString() else type + System.currentTimeMillis()
    }

    fun saveBitmap(bitmap: Bitmap, fileName: String, needRecycle: Boolean): File {
        val file = File(Environment.getExternalStorageDirectory().absolutePath + "/quan11")
        if (!file.exists()) {
            file.mkdirs()
        }
        val realFile = File(file, fileName)
        if (!realFile.exists()) {
            realFile.createNewFile()
        }
        val fos = FileOutputStream(realFile)
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos)
        fos.flush()
        fos.close()
        if (!bitmap.isRecycled && needRecycle) {
            bitmap.recycle()
            System.gc() // 通知系统回收
        }
        return realFile
    }

    fun bmpToByteArray(bmp: Bitmap, needRecycle: Boolean): ByteArray {
        var i: Int
        var j: Int
        if (bmp.height > bmp.width) {
            i = bmp.width
            j = bmp.width
        } else {
            i = bmp.height
            j = bmp.height
        }
        val localBitmap = Bitmap.createBitmap(i, j, Bitmap.Config.RGB_565)
        val localCanvas = Canvas(localBitmap)

        while (true) {
            localCanvas.drawBitmap(bmp, Rect(0, 0, i, j), Rect(0, 0, i, j), null)
            if (needRecycle)
                bmp.recycle()
            val localByteArrayOutputStream = ByteArrayOutputStream()
            localBitmap.compress(Bitmap.CompressFormat.JPEG, 100,
                    localByteArrayOutputStream)
            localBitmap.recycle()
            val arrayOfByte = localByteArrayOutputStream.toByteArray()
            try {
                localByteArrayOutputStream.close()
                return arrayOfByte
            } catch (e: Exception) {
                //F.out(e);
            }

            i = bmp.height
            j = bmp.height
        }
    }

    fun createRandomNum(): String {
        return (Math.random() * 10).toInt().toString()
    }

    //把白色转换成透明
    fun getImageToChange(mBitmap: Bitmap): Bitmap {
        val createBitmap = Bitmap.createBitmap(mBitmap.width, mBitmap.height, Bitmap.Config.ARGB_8888)
        val mWidth = mBitmap.width
        val mHeight = mBitmap.height
        for (i in 0 until mHeight) {
            for (j in 0 until mWidth) {
                var color = mBitmap.getPixel(j, i)
                val g = Color.green(color)
                val r = Color.red(color)
                val b = Color.blue(color)
                var a = Color.alpha(color)
                if (g >= 250 && r >= 250 && b >= 250) {
                    a = 0
                }
                color = Color.argb(a, r, g, b)
                createBitmap.setPixel(j, i, color)
            }
        }
        return createBitmap
    }

    fun evaluate(fraction: Float, startValue: Int?, endValue: Int?): Int {
        val startInt = startValue as Int
        val startA = (startInt shr 24 and 0xff) / 255.0f
        var startR = (startInt shr 16 and 0xff) / 255.0f
        var startG = (startInt shr 8 and 0xff) / 255.0f
        var startB = (startInt and 0xff) / 255.0f

        val endInt = endValue as Int
        val endA = (endInt shr 24 and 0xff) / 255.0f
        var endR = (endInt shr 16 and 0xff) / 255.0f
        var endG = (endInt shr 8 and 0xff) / 255.0f
        var endB = (endInt and 0xff) / 255.0f

        // convert from sRGB to linear
        startR = Math.pow(startR.toDouble(), 2.2).toFloat()
        startG = Math.pow(startG.toDouble(), 2.2).toFloat()
        startB = Math.pow(startB.toDouble(), 2.2).toFloat()

        endR = Math.pow(endR.toDouble(), 2.2).toFloat()
        endG = Math.pow(endG.toDouble(), 2.2).toFloat()
        endB = Math.pow(endB.toDouble(), 2.2).toFloat()

        // compute the interpolated color in linear space
        var a = startA + fraction * (endA - startA)
        var r = startR + fraction * (endR - startR)
        var g = startG + fraction * (endG - startG)
        var b = startB + fraction * (endB - startB)

        // convert back to sRGB in the [0..255] range
        a *= 255.0f
        r = Math.pow(r.toDouble(), 1.0 / 2.2).toFloat() * 255.0f
        g = Math.pow(g.toDouble(), 1.0 / 2.2).toFloat() * 255.0f
        b = Math.pow(b.toDouble(), 1.0 / 2.2).toFloat() * 255.0f

        return Math.round(a) shl 24 or (Math.round(r) shl 16) or (Math.round(g) shl 8) or Math.round(b)
    }

    fun setWindowStatusBarColor(activity: Activity, colorResId: Int) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                val window = activity.window
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
                window.statusBarColor = activity.resources.getColor(colorResId)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun checkUserLogin(): Boolean {
        return if (AppUtils.getString(Contacts.USERID, "") == "") {
            ToastUtil.getInstance().showToast("用户未登录")
            false
        } else true
    }

    /**
     * 版本名
     */
    fun getVersionName(): String {
        return getPackageInfo(MyApplication.getContext())!!.versionName
    }

    private fun getPackageInfo(context: Context): PackageInfo? {
        var pi: PackageInfo? = null

        try {
            val pm = context.packageManager
            pi = pm.getPackageInfo(context.packageName,
                    PackageManager.GET_CONFIGURATIONS)

            return pi
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return pi
    }

    private val ENCODE = "UTF-8"
    /**
     * URL 解码
     *
     * @return String
     * @author lifq
     * @date 2015-3-17 下午04:09:51
     */
    fun getURLDecoderString(str: String?): String {
        var result = ""
        if (null == str) {
            return ""
        }
        try {
            result = java.net.URLDecoder.decode(str, ENCODE)
        } catch (e: UnsupportedEncodingException) {
            e.printStackTrace()
        }

        return result
    }

    /**
     * URL 编码
     *
     * @return String
     * @author lifq
     * @date 2015-3-17 下午04:10:28
     */
    fun getURLEncoderString(str: String?): String {
        var result = ""
        if (null == str) {
            return ""
        }
        try {
            result = java.net.URLEncoder.encode(str, ENCODE)
        } catch (e: UnsupportedEncodingException) {
            e.printStackTrace()
        }

        return result
    }

    /**
     * 判断MainActivity是否活动
    */
    fun isMainActivityAlive(context:Context, activityName:String):Boolean{
       try {
           val  am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
           val  list = am.getRunningTasks(100)
           for ( info in list) {
               Log.e("eeee","栈中的activity是:${info.topActivity}")
               // 注意这里的 topActivity 包含 packageName和className，可以打印出来看看
               if (info.topActivity.toString().contains(activityName)  || info.baseActivity.toString().contains(activityName)) {
                   i("eeee",info.topActivity.packageName + " info.baseActivity.getPackageName()="+info.baseActivity.packageName)
                   return true
               }
           }
       }catch (e:Exception){
           return false
       }
       return false
    }

    fun getBitmapOption(inSampleSize: Int): BitmapFactory.Options {
        System.gc()
        val options = BitmapFactory.Options()
        options.inPurgeable = true
        options.inSampleSize = inSampleSize
        return options
    }

    @SuppressLint("ObsoleteSdkInt")
    fun isNavigationBarShow(act: Activity): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            val display = act.windowManager.defaultDisplay
            val size = Point()
            val realSize = Point()
            display.getSize(size)
            display.getRealSize(realSize)
            realSize.y != size.y
        } else {
            val menu = ViewConfiguration.get(act).hasPermanentMenuKey()
            val back = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK)
            !(menu || back)
        }
    }
    fun getNavigationBarHeight(act: Activity): Int {
        return if (isNavigationBarShow(act)) {
            val rid = act.resources.getIdentifier("config_showNavigationBar", "bool", "android")
            if (rid != 0) {
                val resources = act.resources
                val resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android")
                val height = resources.getDimensionPixelSize(resourceId)
                //Log.v("navigation bar>>>", "height:$height")
                height
            } else 0
        } else 0
    }
    /**
     *获取状态栏高度
     * */
    fun getStatusBarHeight(act: Activity): Int {
        val resources = act.resources
        val resourceId = resources.getIdentifier("status_bar_height", "dimen", "android")
        return if (resourceId>0) {
            val height = resources.getDimensionPixelSize(resourceId)
            height
        } else 0
    }
    fun isApkInstalled(context: Context, packageName: String): Boolean {
        if (TextUtils.isEmpty(packageName)) {
            return false
        }
        return try {
            val info = context.packageManager.getApplicationInfo(packageName, PackageManager.GET_UNINSTALLED_PACKAGES)
            true
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
            false
        }
    }

    /**
     * 复制单个文件
     * @param oldPath String 原文件路径 如：c:/fqf.txt
     * @param newPath String 复制后路径 如：f:/fqf.txt
     * @return boolean
     */
    fun copyFile(oldPath: String, newPath: String): File? {
        try {
            var bytesum = 0
            var byteread = 0
            val oldfile = File(oldPath)
            if (oldfile.exists()) { //文件存在时
                val inStream = FileInputStream(oldPath) //读入原文件
                val fs = FileOutputStream(Environment.getExternalStorageDirectory().absolutePath + "/fuquan$newPath")
                val buffer = ByteArray(1444)
                val length: Int
                while (true) {
                    byteread = inStream.read(buffer)
                    if (byteread != -1) {
                        bytesum += byteread //字节数 文件大小
                        println(bytesum)
                        fs.write(buffer, 0, byteread)
                    } else {
                        break
                    }
                }
                inStream.close()
            }
            return File(Environment.getExternalStorageDirectory().absolutePath + "/fuquan$newPath")
        } catch (e: Exception) {
            println("复制单个文件操作出错")
            e.printStackTrace()
            return null
        }
    }

    /**
     * 纵向拼接bitmap
     * <功能详细描述>
     * @param first
     * @param second
     * @return 
     */
    fun addBitmap(first: Bitmap, second: Bitmap, third: Bitmap): Bitmap {
        val width = Math.max(first.width, second.width)
        val height = first.height + second.height + third.height
        val result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(result)
        canvas.drawBitmap(first, 0f, 0f, null)
        canvas.drawBitmap(second, 0f, first.height.toFloat(), null)
        canvas.drawBitmap(third, 0f, first.height.toFloat() + second.height.toFloat(), null)
        return result
    }

    fun getNumStr(i: Int): String {
        return if (i < 10) "0$i" else i.toString()
    }

    fun changeDrawableColor(context: Context, @DrawableRes drawableId: Int, color: Int): Drawable {
        val drawable = ContextCompat
                .getDrawable(context, drawableId)!!
                .mutate()
        val wrappedDrawable = DrawableCompat.wrap(drawable)
        val colors = ColorStateList.valueOf(color)
        DrawableCompat.setTintList(wrappedDrawable, colors)
        return wrappedDrawable
    }

    fun setViewPagerScroller(context: Context, viewPager: ViewPager) {
        try {
            val scrollerField = ViewPager::class.java.getDeclaredField("mScroller")
            scrollerField.isAccessible = true
            val interpolator = ViewPager::class.java.getDeclaredField("sInterpolator")
            interpolator.isAccessible = true

            val scroller = object : Scroller(context, interpolator.get(null) as android.view.animation.Interpolator) {
                override fun startScroll(startX: Int, startY: Int, dx: Int, dy: Int, duration: Int) {
                    super.startScroll(startX, startY, dx, dy, duration * 3)    // 这里是关键，将duration变长或变短
                }
            }
            scrollerField.set(viewPager, scroller)
        } catch (e: NoSuchFieldException) {
            // Do nothing.
        } catch (e: IllegalAccessException) {
            // Do nothing.
        }
    }

    fun hideInputBoard(context: Context, view: View) {
        val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        //  imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);//SHOW_FORCED表示强制显示
        imm.hideSoftInputFromWindow(view.windowToken, 0) //强制隐藏键盘
    }
    fun encodeImage(bitmap: Bitmap): String {
        val baos = ByteArrayOutputStream()
        //读取图片到ByteArrayOutputStream
        bitmap.compress(Bitmap.CompressFormat.JPEG, 40, baos) //参数如果为100那么就不压缩
        val bytes = baos.toByteArray()
        return Base64.encodeToString(bytes, Base64.DEFAULT)
    }

    //将ascii码转字符
    fun asciiToString(value: String): String {
        val sbu = StringBuffer()
        val chars = value.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
        for (i in chars.indices) {
            sbu.append(Integer.parseInt(chars[i]).toChar())
        }
        return sbu.toString()
    }

    /**
     * 拨打电话（跳转到拨号界面，用户手动点击拨打）
     *
     * @param phoneNum 电话号码
     */
    fun callPhone(context: Context, phoneNum: String) {
        val intent = Intent(Intent.ACTION_DIAL)
        val data = Uri.parse("tel:$phoneNum")
        intent.data = data
        context.startActivity(intent)
    }
    fun parseGood(item: UserCenterGoodBean.RecordsBean): TaobaoGoodBean {
        val commissionRatio=DataUtils().getCommissionRatio()
        val good = TaobaoGoodBean()
        good.isUserCenter = true
        good.shop_title = item.shopTitle
        good.title = item.title
        good.has_coupon = item.couponAmount != ""
        good.commission_rate = item.commissionRate
        good.coupon_remain_count = item.couponRemainCount
        //good.coupon_share_url="https:${item.couponClickUrl}"//item.couponClickUrl
        //good.coupon_share_url_new = "https:${item.couponClickUrl}"
        good.url = "https:${item.clickUrl}"
        good.num_iid = item.itemId
        good.pict_url = "http:${item.pictUrl}"
        good.small_images = item.smallImages
        good.user_type = item.userType.toString()
        //good.volume = item.volume.toString()
        good.coupon_price = item.couponAmount
        good.zk_final_price=item.zkFinalPrice
        good.coupon_info = "满${item.couponStartFee}元减${item.couponAmount}元"
        good.original_price = item.zkFinalPrice
        good.final_price = BigDecimal(item.zkFinalPrice).subtract(BigDecimal(item.couponAmount))
                .setScale(2, BigDecimal.ROUND_HALF_UP).toString()
        if (item.couponClickUrl!=null){
            if (!item.couponClickUrl.startsWith("http")) {
                good.coupon_share_url="https:${item.couponClickUrl}"
                good.coupon_share_url_new = "https:${item.couponClickUrl}"
            }else{
                good.coupon_share_url=item.couponClickUrl
                good.coupon_share_url_new =item.couponClickUrl
            }
        }
        if (item.couponStartTime.isNotEmpty()){
            val date=Date(item.couponStartTime.toLong())
            try {
                good.coupon_start_time=simpleDateFormat.format(date)
            }catch (e:Exception){
                good.coupon_start_time=""
            }
        }else{
            good.coupon_start_time=""
        }
        if (item.couponEndTime.isNotEmpty()){
            val date=Date(item.couponEndTime.toLong())
            try {
                good.coupon_end_time=simpleDateFormat.format(date)
            }catch (e:Exception){
                good.coupon_end_time=""
            }
        }else{
            good.coupon_end_time=""
        }
        when(item.userType){
            0->{
                good.userType= R.drawable.goods_tb
                good.goodsSource="淘宝"
            }
            1->{
                good.userType= R.drawable.goods_tm
                good.goodsSource="天猫"
            }
        }
        good.volume =if (item.volume>10000){
            "月销"+df.format((item.volume).toDouble()/10000)+"万"
        }else{
            "月销"+item.volume
        }
        if (good.small_images != null &&
                good.small_images!!.toString() != "" &&
                good.small_images!!.toString() != "[]") {
            var array = good.small_images!!.toString()
            array = array.substring(1, array.length)
            if (!array.contains(",")) {
                good.images.add("http:${array.trim()}")
            } else {
                val images = array.substring(1, array.length - 1).split(",")
                for (i in 0 until images.size){
                    val image=images[i].trim()
                    if (image.startsWith("http")){
                        good.images.add(image)
                    }else{
                        good.images.add("https:$image")
                    }
                }
            }
        }

        val commission = BigDecimal(good.final_price)
                .multiply(BigDecimal(good.commission_rate))
                .multiply(RETURN_RATIO.toBigDecimal())
                .divide(BigDecimal(100))

        val vipBuyCommission = commission
                .multiply(commissionRatio.toBigDecimal())

        val vipShareCommission = commission
                .multiply(commissionRatio.toBigDecimal())

        val svipBuyCommission = commission
                .multiply(commissionRatio.toBigDecimal())

        val svipShareCommission = commission
                .multiply(commissionRatio.toBigDecimal())
        good.vip_commission = vipBuyCommission
                .setScale(2, BigDecimal.ROUND_HALF_UP)
                .toString()

        good.svip_commission = svipBuyCommission
                .setScale(2, BigDecimal.ROUND_HALF_UP)
                .toString()
        /*good.vip_commission = vipBuyCommission.add(vipShareCommission)
                .setScale(2, BigDecimal.ROUND_HALF_UP)
                .toString()

        good.svip_commission = svipBuyCommission.add(svipShareCommission)
                .setScale(2, BigDecimal.ROUND_HALF_UP)
                .toString()*/

        return good
    }

    fun parseGood1(item: TaobaoTablePageBean.RecordsBean): TaobaoGoodBean {
        val good = TaobaoGoodBean()
        val commissionRatio=DataUtils().getCommissionRatio()
        good.commission_rate = item.tkRate
        good.coupon_share_url = if (item.couponClickUrl != null) item.couponClickUrl!! else ""
        good.url = if (item.clickUrl != null) item.clickUrl!! else ""

        good.shop_title = ""
        good.title = item.title
        good.coupon_info = if (item.couponInfo != null) item.couponInfo!! else ""
        good.coupon_remain_count = if (item.couponRemainCount != null) item.couponRemainCount!! else ""
        good.num_iid = item.numIid
        good.pict_url = item.pictUrl
        good.small_images = item.smallImages
        good.user_type = item.userType
        good.volume = item.volume
        good.zk_final_price = item.zkFinalPrice
        good.reserve_price = item.reservePrice

        if (good.coupon_info != "") {
            good.has_coupon = true
            val start = good.coupon_info.indexOf("减")
            val str = good.coupon_info.substring(start + 1)
            val end = str.indexOf("元")
            good.coupon_price = str.substring(0, end)
            val couponFinalPrice = BigDecimal(good.zk_final_price).subtract(BigDecimal(good.coupon_price)).setScale(2, BigDecimal.ROUND_HALF_UP)
            good.final_price = if (couponFinalPrice > BigDecimal.ZERO) couponFinalPrice.toString() else "0"
            good.original_price = good.zk_final_price
        } else {
            good.final_price = good.zk_final_price
            good.original_price = good.reserve_price
        }
        val commission = BigDecimal(good.final_price)
                .multiply(BigDecimal(good.commission_rate))
                .multiply(RETURN_RATIO.toBigDecimal())
                .divide(BigDecimal(10000))

        val vipBuyCommission = commission
                .multiply(commissionRatio.toBigDecimal())

        val vipShareCommission = commission
                .multiply(commissionRatio.toBigDecimal())

        val svipBuyCommission = commission
                .multiply(commissionRatio.toBigDecimal())

        val svipShareCommission = commission
                .multiply(commissionRatio.toBigDecimal())
        good.vip_commission = vipBuyCommission
                .setScale(2, BigDecimal.ROUND_HALF_UP)
                .toString()

        good.svip_commission = svipBuyCommission
                .setScale(2, BigDecimal.ROUND_HALF_UP)
                .toString()
        /*good.vip_commission = vipBuyCommission.add(vipShareCommission)
                .setScale(2, BigDecimal.ROUND_HALF_UP)
                .toString()

        good.svip_commission = svipBuyCommission.add(svipShareCommission)
                .setScale(2, BigDecimal.ROUND_HALF_UP)
                .toString()*/

        if (good.small_images != null &&
                good.small_images!!.toString() != "" &&
                good.small_images!!.toString() != "[]") {
            var array = good.small_images!!.toString()
            array = array.substring(0, array.length)
            if (!array.contains(",")) {
                good.images.add(array.trim())
            } else {
                val images = array.substring(1, array.length - 1).split(",")
                for (i in 0 until images.size){
                    val image=images[i].trim()
                    if (image.startsWith("http")){
                        good.images.add(image)
                    }else{
                        good.images.add("https:$image")
                    }
                }
            }
        }
        return good
    }
}